package cn.chendd.example.jpa.configuration;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.springframework.data.spel.spi.EvaluationContextExtension;
import org.springframework.data.spel.spi.Function;
import org.springframework.stereotype.Component;

import javax.persistence.Transient;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author chendd
 * @date 2022/6/19 23:54
 */
@Component
public class JpaEvaluationContextExtension implements EvaluationContextExtension {

    @Override
    public String getExtensionId() {
        return "cdd";
    }

    @Override
    public Map<String, Function> getFunctions() {
        Map<String , Function> maps = Maps.newHashMap();
        Method[] methods = MethodUtils.getMethodsWithAnnotation(ConditionFunctions.class, Transient.class);
        if (methods != null) {
            for (Method method : methods) {
                maps.put(method.getName() , new Function(method));
            }
        }
        return maps;
    }

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> map = Maps.newHashMap();
        map.put("chendd" , "666");
        return map;
    }

    /**
     * 自定义方法类
     *
     * @author chendd
     * @date 2022/6/19 23:55
     */
    public static class ConditionFunctions {

        @Transient
        public static String hello() {
            return "hello chendd";
        }

    }

}
